package controller

import (
	"context"
	"errors"
	"fmt"
	"gitee.com/we7coreteam/w7-im-websocket-push/app/home/logic"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"github.com/gorilla/websocket"
	"github.com/we7coreteam/w7-rangine-go-support/src/facade"
	"github.com/we7coreteam/w7-rangine-go/src/core/err_handler"
	"github.com/we7coreteam/w7-rangine-go/src/http/controller"
	"log"
)

type Home struct {
	controller.Abstract
}

func (home Home) Ws(ctx *gin.Context, wsCollection *logic.Collection) {
	if !websocket.IsWebSocketUpgrade(ctx.Request) {
		home.JsonResponseWithError(ctx, errors.New("请使用 ws 连接"), 500)
		return
	}
	token, found := ctx.GetQuery("token")
	if !found || token == "" {
		home.JsonResponseWithError(ctx, errors.New("缺少 Token 参数"), 500)
		return
	}

	// 验证 token
	myUserInfo := logic.UserInfo{}
	jwtToken, err := jwt.ParseWithClaims(token, &myUserInfo, func(token *jwt.Token) (interface{}, error) {
		return []byte(facade.GetConfig().GetString("jwt.key")), nil
	}, jwt.WithValidMethods([]string{"HS256"}))

	if err_handler.Found(err) || !jwtToken.Valid {
		log.Println("jwt 解析错误:", err.Error())
		home.JsonResponseWithError(ctx, err, 500)
		return
	}

	log.Println("用户登录:", myUserInfo.User.Id, myUserInfo.User.UserName)

	client, err := logic.NewClientConn(ctx)
	if err_handler.Found(err) {
		home.JsonResponseWithError(ctx, err, 500)
		return
	}
	goCtx, cancelFunc := context.WithCancel(context.Background())

	client.Fd = fmt.Sprintf("%d_%s_%s_%s::%s", myUserInfo.User.Id, myUserInfo.User.Roles, myUserInfo.User.Channel, myUserInfo.User.Source, wsCollection.ServerHostName)
	client.Token = token
	client.CancelFunc = func(client *logic.Client) {
		wsCollection.Destroy(client)
	}
	client.PullMsgFunc = func(message string) {
		wsCollection.Pull(message)
	}
	client.CtxContext = goCtx
	client.CtxCancelFunc = cancelFunc

	wsCollection.Register(client)

	go client.ReadMessage()
	go client.SendMessage()
}
